package cn.wolfcode.shop.cloud.mq.listener;

import cn.wolfcode.shop.cloud.common.JSONUtil;
import cn.wolfcode.shop.cloud.common.Result;
import cn.wolfcode.shop.cloud.core.WebSocketServer;
import cn.wolfcode.shop.cloud.mq.MQConstants;
import cn.wolfcode.shop.cloud.mq.msg.SeckillSuccessMsg;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.stereotype.Component;

import javax.websocket.Session;

/**
 * Created by wolfcode-lanxw
 */
@Slf4j
@Component
@RocketMQMessageListener(
        topic = MQConstants.SECKILL_ORDER_TOPIC,
        selectorExpression = MQConstants.SECKILL_SUCCESS_TAG,
        consumerGroup = MQConstants.SECKILL_SUCCESS_CONSUMER_GROUP
)
public class SeckillSuccessMQListener implements RocketMQListener<SeckillSuccessMsg> {

    @Override
    public void onMessage(SeckillSuccessMsg message) {
        log.info("[秒杀成功监听器] 收到秒杀订单成功消息:{}", JSONUtil.toJSONString(message));
        try {
            // 根据经uuid找到对应的客户端
            // 最大重试次数
            int max_retries = 3;
            Session session = null;
            do {
                session = WebSocketServer.clients.get(message.getUuid());
                if (session == null) {
                    // 如果当前获取不到才睡500毫秒
                    Thread.sleep(500);
                }
                // 重试次数-1
                max_retries--;
            } while (session == null && max_retries >= 0);

            if (session != null) {
                // 包装result对象, 转换成json格式
                Result<SeckillSuccessMsg> result = Result.success(message);
                // 发送给前端
                session.getBasicRemote().sendText(JSONUtil.toJSONString(result));
            } else {
                log.warn("[秒杀成功监听器] 通知前端消息失败, 无法获取到用户:{}的连接", message.getUuid());
            }
        } catch (Exception e) {
            log.error("[秒杀成功监听器] 通知前端消息失败", e);
        }
    }
}
